package tongwentongshu.com.app.utils;


import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import java.io.File;

import tongwentongshu.com.app.BuildConfig;

/**
 * Created by XiongBin on 2017/8/9.
 */

public class VersionUpdataUtil {

    public static final String GET_VERSION_URL = "http://api.fir.im/apps/latest/595d9a97ca87a845cf0001d8?api_token=189d57610ae9094822d2c7b114fb88cd";
    public static final String FILES_DIR = Environment.getExternalStorageDirectory() + "/DownLoad/APK/"; //文件下载路径

    /**
     * 获取应用的包名
     */
    public static String getPackageName(Context context) {
        return context.getPackageName();
    }

    /**
     * 获取应用的版本号
     */
    public static int getVersionCode(Context context) {
        int versionCode1 = 0;
        try {
            if (context.getPackageManager() != null) {
                // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
                versionCode1 = context.getPackageManager().getPackageInfo(
                        getPackageName(context), 0).versionCode;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode1;
    }

    /**
     * 获取应用的版本名称
     */
    public static String getVersionName(Context context) {
        String versionName = "";
        try {
            if (context.getPackageManager() != null) {
                // 获取软件版本号，对应AndroidManifest.xml下android:versionName
                versionName = context.getPackageManager().getPackageInfo(
                        getPackageName(context), 0).versionName;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }


    /**
     * 创建文件的存储路径
     */
    public static String createFilePath(String fileName) {
        String dir = FILES_DIR;
        File destDir = new File(dir);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        File file = null;
        if (!TextUtils.isEmpty(fileName)) {
            file = new File(dir, fileName);
        }
        return file != null ? file.getAbsolutePath() : null;
    }

    /**
     * 打开文件
     * 兼容7.0
     *
     * @param context     activity
     * @param file        File
     * @param contentType 文件类型如：文本（text/html）
     *                    当手机中没有一个app可以打开file时会抛ActivityNotFoundException
     */
    public static void startActionFile(Context context, File file, String contentType) throws ActivityNotFoundException {
        if (context == null) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);//增加读写权限
        intent.setDataAndType(getUriForFile(context, file), contentType);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);

    }

    private static Uri getUriForFile(Context context, File file) {
        if (context == null || file == null) {
            throw new NullPointerException();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }


    /**
     * 判断网络类型
     *
     * @param context 上下文
     * @return 返回值 -1：没有网络  1：WIFI网络2：wap网络3：net网络
     */

    public static int GetNetype(Context context) {
        int netType = -1;
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            if (networkInfo.getExtraInfo().toLowerCase().equals("cmnet")) {
                netType = 3;
            } else {
                netType = 2;
            }
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 1;
        }
        return netType;
    }

    private static long lastClickTime = 0;
    private final static int SPACE_TIME = 500;

    /**
     * 防止多次点击
     */
    public synchronized static boolean isDoubleClick() {
        long currentTime = System.currentTimeMillis();
        boolean isClick2;
        isClick2 = currentTime - lastClickTime >= SPACE_TIME;
        lastClickTime = currentTime;
        return isClick2;
    }

}
